package cn.edu.scnu.semart.order.service.impl;

import cn.edu.scnu.semart.order.feign.UserFeignClient;
import cn.edu.scnu.semart.order.mapper.OrderStatMapper;
import cn.edu.scnu.semart.order.service.OrderStatService;
import cn.edu.scnu.semart.vo.order.RegionSalesVO;
import cn.edu.scnu.semart.vo.order.TradeDailyVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import cn.edu.scnu.semart.model.user.Address;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class OrderStatServiceImpl implements OrderStatService {

    private final OrderStatMapper orderStatMapper;
    private final UserFeignClient userFeignClient;

    @Override
    public List<RegionSalesVO> regionSales() {
        List<Address> addresses = userFeignClient.getAllAddresses();
        Map<String, Long> provinceCount = new HashMap<>();
        for (Address address : addresses) {
            String province = address.getProvince();
            provinceCount.put(province, provinceCount.getOrDefault(province, 0L) + 1);
        }
        List<RegionSalesVO> result = new ArrayList<>();
        for (Map.Entry<String, Long> entry : provinceCount.entrySet()) {
            RegionSalesVO vo = new RegionSalesVO();
            vo.setRegion(entry.getKey());
            vo.setSales(entry.getValue().intValue());
            result.add(vo);
        }
        return result;
    }

    private Map<String, Object> createRegion(String region, int sales) {
        Map<String, Object> map = new HashMap<>();
        map.put("region", region);
        map.put("sales", sales);
        return map;
    }

    @Override
    public List<TradeDailyVO> tradeDaily() {
        List<Map<String, Object>> dailyList = orderStatMapper.countOrderDaily();
        List<TradeDailyVO> result = new ArrayList<>();
        for (Map<String, Object> map : dailyList) {
            TradeDailyVO vo = new TradeDailyVO();
            vo.setDate(map.get("date").toString());
            vo.setOrderCount(((Number) map.get("orderCount")).intValue());
            vo.setTotalAmount(((Number) map.get("totalAmount")).doubleValue());
            result.add(vo);
        }
        return result;
    }
}